package com.jiazhong.spring.rocketmq.普通消息.生产.异步消息;

import lombok.SneakyThrows;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

public class 异步消息发送 {
    @SneakyThrows
    public static void main(String[] args) {
        // 1.创建消息生产者 producer，并指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("producer_group_a");
        // 2.指定 NameSrv 地址
        producer.setNamesrvAddr("124.220.170.254:9876");
        // 3.启动 producer
        producer.start();
        for (int i = 1; i < 21; i++) {
            // 4.创建消息对象，指定 Topic、Tag 和消息体
            String topic = "TopicA";
            String tags = "async";
            String body = "Hello,Async!index:" + i;
            Message message = new Message(topic, tags, body.getBytes());
            // 5.发送消息
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送失败");
                }
            });
        }
        Thread.sleep(10000);
        // 6.关闭生产者 producer
        producer.shutdown();
    }
}
